package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.common.Result;
import com.example.demo.entity.ACMKey;
import com.example.demo.mapper.ACMKeyMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/ACMKey")
public class ACMKeyController {

    @Resource
    ACMKeyMapper ACMKeyMapper;

    @PostMapping  //增
    public Result<?> save(@RequestBody ACMKey ACMKey) {
        ACMKeyMapper.insert(ACMKey);
        return Result.success();
    }

    @DeleteMapping("/{id}") //删
    public Result<?> delete(@PathVariable long id) {
        ACMKeyMapper.deleteById(id);
        return Result.success();
    }

    @GetMapping //获得按难易排行的知识点
    public Result<?> GetMethodSort() {

        QueryWrapper queryWrapper = new QueryWrapper();
        QueryWrapper queryWrapper2 = new QueryWrapper();

        queryWrapper.select("DISTINCT Method");
        List<ACMKey> acmKeyList = ACMKeyMapper.selectList(queryWrapper);

        List<ACMKey> acmKeys = ACMKeyMapper.selectList(queryWrapper2);
        List<Map<String,Object>> methodMap = new ArrayList<>();
        for(int i=0;i<acmKeyList.size();i++) {
            float passRatio = 0;
            String method = acmKeyList.get(i).getMethod();
            int t=0;
            System.out.println(method);
            for (int j = 0; j < acmKeys.size(); j++) {
                if(acmKeys.get(j).getMethod().equals(method)){
                    t++;
                    passRatio += acmKeys.get(j).getPassRatio();
                }

            }

            Map<String,Object> map = new HashMap<>();
            map.put("method",method);
            map.put("passRatio",(passRatio/t));
            methodMap.add(map);
        }

        methodMap=methodMap.stream().sorted(Comparator.comparing(MapCompare::comparingByPassRatio).reversed())
                .collect(Collectors.toList());


        List<Map<String,Object>> newList = methodMap.subList(0, 10);//取前最容易学习排行10条
        return Result.success(newList);

//        return Result.success(methodMap);//所有知识点
    }



    @PutMapping //改
    public Result<?> update(@RequestBody ACMKey ACMKey) {
        ACMKeyMapper.updateById(ACMKey);
        return Result.success();
    }
}
class MapCompare {

    public static Float comparingByPassRatio(Map map){
        return (Float) map.get("passRatio");
    }

}
